<template>
  <div class="search-form" :class="{boxShadow}">
    <div class="top-search">
      <div class="form-item" v-for="(item, i) in searchArray" :key="i">
        <span class="label"  v-if="item.label" :class="{nomargin: i == 0, noLeng: item.label && item.label.indexOf('：') == -1}">{{item.label}}</span>
        <input
          v-if="item.type == 'input'"
          v-model.trim="item.value"
          :type="item.types || 'text'"
          class="input"
          :placeholder="item.placeholder"
          :style="{width: item.width ? item.width : '200px'}"
          @input="inputs($event.target.value, item.key)"
        />
        <el-select class="el-selects" v-model="item.value" :multiple="item.multiple || false" v-if="item.type == 'select'" filterable :style="{width: !item.width ? '200px' : item.width}" @change="changeSelect" @focus="getCurent(item)">
          <el-option v-for="(items, ii) in item.list" :key="ii" :value="items.value" :label="items.label"></el-option>
        </el-select>
        <el-date-picker
          v-if="item.type == 'datePicker'"
          v-model="item.value"
          :type="item.types"
          :range-separator="item.rangeSpeparator"
          :start-placeholder="item.startText"
          :end-placeholder="item.endText"
          :picker-options="pickerOptions"
          @change="changeDateTime"
          @focus="getCurent(item)"
        ></el-date-picker>
        <el-radio-group
          v-model="item.value"
          v-if="item.type =='radioGroup'"
          style="margin-left: 16px;"
          v-show="false"
        >
          <el-radio :label="items.value" v-for="(items, ii) in item.list" :key="ii">{{items.label}}</el-radio>
        </el-radio-group>
        <div class="selection-group" v-if="item.type == 'sectionValue'">
          <div class="group-box">
            <div class="group-item">
              <span class="unit" v-if="item.unit">{{item.unit}}</span>
              <input type="text" @input="inputs($event.target.value, item.key1)" v-model.trim="item.value1" :placeholder="item.pl1 || ''"/>
            </div>
            <span class="split">-</span>
            <div class="group-item">
              <span class="unit" v-if="item.unit">{{item.unit}}</span>
              <input type="text" @input="inputs($event.target.value, item.key1)" v-model.trim="item.value2" :placeholder="item.pl2 || ''"/>
            </div>
          </div>
        </div>
        <area-select v-if="item.type == 'area'" :area="item.value" @handleChange="handleChange" @focus="getCurent(item)"></area-select>
        <slot v-if="item.type == 'slot'" :name="item.slotName"></slot>
      </div>
      <el-button @click="search"  class="btn search maR insearch" >搜索</el-button>
      <el-button @click="clear" class="btn success  maR insearch" >清空</el-button>
      <slot></slot>
    </div>
  </div>
</template>
<script>
import areaSelect from '../xForm/areaSelect'
export default {
  name: "searchForm",
  components: {
      areaSelect
  },
  props: {
    searchObj: {
      type: Object
    },
    boxShadow: {
      type: Boolean,
      default () {
        return true
      }
    },
    searchArray: {
      type: Array,
      default() {
        return [
          {
            type: "input",
            placeholder: "请输入",
            types: "text",
            value: "",
            label: "关键词："
          },
          {
            type: 'area',
            value: [], // 数组 
            label: '',
            key1: '',
            key2: '',
            key3: ''
          },
          {
            type: "select",
            placeholder: "请选择",
            filterable: false,
            multiple: false,
            value: "",
            width: '',
            list: [
              {
                label: "",
                value: ""
              }
            ]
          },
          {
            type: "datePicker",
            startText: "开始日期",
            endText: "结束日期",
            types: "datetimerange",
            value: "",
            rangeSpeparator: "至",
            key1: '',
            key2: ''
          },
          {
            type: "radioGroup",
            value: "",
            list: [
              {
                label: "今日",
                value: "day"
              },
              {
                label: "明日",
                value: "days"
              }
            ]
          },
          {
            type: "sectionValue",
            value1: "",
            value2: "",
            label: "金额区间：",
            unit: "",
            key1: "",
            key2: "",
            pl1: '',
            pl2: ''
          }
        ];
      }
    }
  },
  data() {
    let _this = this
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              let nyr = _this.$moment(new Date()).format('YYYY-MM-DD')
              picker.$emit("pick", [new Date(nyr +' 00:00:00'), new Date(nyr+' 23:59:59')]);
            }
           },
          {
            text: "昨天",
            onClick(picker) {
              let date = _this.$moment(new Date()).format('YYYY-MM-DD')
              let arr = date.split('-')
              let nyr = arr[0]+'-'+arr[1]+'-'+ ((new Date()).getDate() -1)
              picker.$emit("pick", [new Date(nyr +' 00:00:00'), new Date(nyr+' 23:59:59')]);
            }
          },
          {
            text: "近7天",
            onClick(picker) {
              const start = new Date();
              start.setDate(start.getDate()-6);
              picker.$emit("pick", [start, new Date()]);
            }
          },
          {
            text: "近30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      currentObj: {}
    };
  },
  mounted () {
    this.bindKeyup()
  },
  methods: {
    inputs (val, key) {
      this.searchObj[key] = val
    },
    changeDateTime (val) {
      const {currentObj: {key1, key2}} = this
      if (key1) {
        this.$set(this.searchObj, key1, this.$moment(new Date(val[0])).format('YYYY-MM-DD HH:mm:ss'))
      }
      if (key2) {
        this.$set(this.searchObj, key2, this.$moment(new Date(val[1])).format('YYYY-MM-DD HH:mm:ss'))
      }
    },
    search() {
      const { searchArray } = this;
      let obj = {};
      searchArray.forEach(r => {
        if (r.type == "sectionValue") {
          obj[r.key1] = r.value1;
          obj[r.key2] = r.value2;
        } else {
          obj[r.key] = r.value;
        }
      });
      this.$emit("search", false);
    },
    clear() {
      let { searchArray } = this
      let obj = {}
      searchArray.forEach(r => {
        if (r.type == "sectionValue") {
          obj[r.key1] = ""
          obj[r.key2] = ""
          r.value1 = ""
          r.value2 = ""
        } else if (r.type == 'area') {
          obj[r.key1] = ""
          obj[r.key2] = ""
          obj[r.key3] = ""
          this.$set(r.value, 'value', [])
        } else {
          obj[r.key] = ""
          r.value = ""
        }
      });
      for (let k in this.searchObj) {
        this.searchObj[k] = ''
      }
      this.$emit("clear", obj)
      setTimeout(() => {
        this.$emit('search', false)
      }, 100)
    },
    changeSelect (val) {
      const {currentObj} = this
      if (currentObj.key) {
        this.$set(this.searchObj, currentObj.key, val)
      }
      if (currentObj.needChange) {
        this.$emit('change', currentObj)
      }
    },
    handleChange (val) {
      const {currentObj: {key1, key2, key3}} = this
      this.searchObj[key1] = val[0]
      this.searchObj[key2] = val[1]
      this.searchObj[key3] = val[2]
    },
    getCurent (item) {  
      this.currentObj = item
    },
    enterKeyupDestroyed() {
        document.removeEventListener("keyup", this.enterKey)
    },
    enterKey(event) {
        const componentName = this.$options.name;
        if (componentName == "searchForm") {
            const code = event.keyCode
                ? event.keyCode
                : event.which
                    ? event.which
                    : event.charCode
            if (code == 13) {
                this.search()
            }
        }
    },
    bindKeyup () {
      document.addEventListener("keyup", this.enterKey)
    }
  },
  beforeDestroy () {
    this.enterKeyupDestroyed()
  }
};
</script>
<style lang="scss" scoped>
$main-color: #1890ff;
.el-button--text {
    color: $main-color !important;
  }
.search-form {
  background: #fff;
  width: 100%;
  padding: 0 16px;
  &.boxShadow {
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.05);
  }
  .top-search {
    overflow: hidden;
    vertical-align: middle;
    padding-top: 16px;
    &.noborder {
      border: 0;
    }
  }
  .bottom-search {
    padding: 16px 16px 0 0;
  }
  .form-item {
    display: inline-block;
    margin-bottom: 16px;
    vertical-align: top;
    .label {
      display: inline-block;
      font-size: 14px;
      font-weight: 500;
      color: #333;
      min-width: 80px;
      text-align: right;
      &.noLeng {
        margin-right: 8px;
      }
    }
    ::v-deep.input {
      width: 200px;
      height: 32px;
      border: 1px solid #ddd;
      outline: none;
      border-radius: 2px;
      padding-left: 10px;
      vertical-align: middle;
      margin-right: 16px;
    }
    .el-date-editor {
      height: 32px;
      vertical-align: middle;
      margin-right: 16px;
      border-radius: 2px;
      .el-range__icon {
        line-height: 26px;
      }
      .el-range-separator {
         line-height: 22px;
         margin: 0 8px;
      }
    }
  
    ::v-deep.el-select {
      height: 32px;
      line-height: 32px;
      margin-right: 16px;
      .el-input__inner {
        height: 32px;
        border-radius: 2px;
        padding-left: 10px;
      }
      .el-input__icon {
        line-height: 32px;
      }
      .el-input__suffix {
        right: 0;
      }
    }
  }
  .el-button {
    margin-bottom: 16px;
    margin-left: 8px;
    height: 32px;
    padding: 0 16px;
    font-size: 14px;
    min-width: 80px;
    color: $main-color;
    border-color:$main-color;
    &.search {
      margin-left: 0px;
      border-color: $main-color;
      background: $main-color;
      color: #fff;
    }
  }
  .selection-group {
    display: inline-block;
    vertical-align: middle;
    white-space: nowrap;
    margin-right: 16px;
    .group-box {
      display: flex;
      align-items: center;
      .group-item {
        width: 93.5px;
        height: 32px;
        border: 1px solid #ddd;
        line-height: 30px;
        display: flex;
        padding-left: 10px;
        &:hover {
          border-color: #ccc;
        }
        .unit {
          font-size: 14px;
        }
        input {
          flex: 1;
          outline: none;
          height: 100%;
          background: transparent;
          border: 0;
        }
      }
      .split {
        color: #999;
        margin: 0 4px;
        font-size: 12px;
      }
    }
  }
}
</style>